<!-- 大底请购作业：蹇泽阳 -->
<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <div class="flex mt10" style="width: 100%">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }" style="width: 100%">
        <h1 class="f16">汇总材料查询</h1>
        <Table
          @selectList="selectList"
          :tableHeader="tableHeader"
          :tableData="tableData"
          selection
          class="mt10"
          :isLoading="isLoading"
          @currentRow="currentRow"
        />
      </el-card>
    </div>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
    </el-card>

    <!-- 我的订购单 -->
    <MyDingGouDan :obj="parentObj" :drawer="drawer" :getTableList="getTableList" @propsDrawerFalse="() => (drawer = false)" />

    <!-- 所有订购单 -->
    <el-drawer v-model="drawer2" :direction="'ttb'" size="small" :with-header="false">
      <span @click="drawer2 = false" style="float: right; cursor: pointer; color: rgb(7, 7, 7)">X</span>
      <Find :searchImg="false" :formList="formList12" @findClicked="findClicked12" />
      <div class="flex mt10 JCC" style="width: 100%; background-color: white">
        <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
          <h1 class="f16">所有订购单</h1>
          <Table
            :tableHeader="tableHeader12"
            :tableData="tableData12"
            selection
            class="mt10"
            :outTableHeight="150"
            @selectList="selectList12"
            @currentRow="currentRow12"
          />
        </el-card>
      </div>
      <PageModule :PageData="{ buttonS: true, total: total12 }" @pageChange="handleCurrentChange12" @pageSizeChange="handleSizeChange12" />
    </el-drawer>
  </div>
</template>

<script lang="ts" setup name="OutsolePurchaseAssignment">
import { ManufacturerQuery } from '@/api/PurchasingDepartment/FactoryPurchasing/MaterialRequisition'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
import service from '@/utils/request'
import { ElLoading } from 'element-plus'
import { debounce } from 'lodash'
import { watch } from 'vue'
import { onMounted } from 'vue'
import { ref } from 'vue'
import { nextTick } from 'vue'
import KouJian from './Components/KouJian.vue'
import MyDingGouDan from './Components/MyDingGouDan.vue'
const printTag = ref({}) as any
const dialogVisible = ref(false)
const drawer = ref(false)
const drawer2 = ref(false)
const parentObj = ref({
  url: 'ddMaterial',
  purTypeFlag: 15
}) as any
const formList = ref([
  {
    type: 'select',
    selectValue: '',
    selectP: '指令',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '分类',
    selectLabel: '',
    selectOptions: [
      {
        optionKey: '1',
        optionValue: '1',
        optionLabel: '汇总'
      },
      {
        optionKey: '2',
        optionValue: '2',
        optionLabel: '差异'
      }
    ]
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料名称',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料颜色',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '材料分类',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'checkbox',
    checkboxLabel: '正数',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '负数',
    checked: true
  },
  {
    type: 'button',
    checkboxLabel: '查询'
  },
  {
    type: 'button',
    checkboxLabel: '置空'
  },
  {
    type: 'button',
    checkboxLabel: '进入我的订购单'
  },
  {
    type: 'button',
    checkboxLabel: '进入所有订购单'
  },
  {
    type: 'button',
    checkboxLabel: '请购批处理'
  }
]) as any

// 表一模块
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '查询') {
    getTableList()
  }
  if (content === '进入我的订购单') {
    drawer.value = true
  }
  if (content === '进入所有订购单') {
    drawer2.value = true
    getTableList12()
  }
  if (content === '选择通用资料') {
    dialogVisible.value = true
    getTableList2()
  }
  if (content === '请购批处理') {
    // 请购批处理
    if (selectTableList.value.length === 0) {
      JMessage.warning('请勾选需要请购批处理的数据')
    } else {
      const res = await service.post<any, any>(`/mes/kf/ddMaterial/makeReqOrder?purTypeFlag=${15}`, selectTableList.value)
      if (res.code === 200) {
        JMessage.success(res.msg)
        getTableList()
      } else {
        JMessage.error(res.msg)
      }
    }
  }
}
const tableData = ref([])
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
const selectTableList = ref([])
const selectList = (val: any) => {
  selectTableList.value = val
}
const tableHeader = ref([
  {
    label: '指令',
    prop: 'lotNo',
    width: '130'
  },
  {
    label: '订单类型',
    prop: 'type'
  },
  {
    label: '纸版号',
    prop: 'shoeName'
  },

  {
    label: '工厂货号',
    prop: 'style'
  },

  {
    label: '品牌',
    prop: 'brand'
  },
  {
    label: '颜色',
    prop: 'color'
  },

  {
    label: '大底',
    prop: 'moldNo'
  },
  {
    label: '尺寸',
    prop: 'sizeNo'
  },


  {
    width: '130',
    label: '物料编码',
    prop: 'mtlNo'
  },
  {
    width: '130',
    label: '材料名称',
    prop: 'mtlName'
  },
  {
    label: '材料颜色',
    prop: 'mtlColor'
  },
  {
    label: '规格',
    prop: 'mtlSpec'
  },
  {
    label: '单位',
    prop: 'mtlUnit'
  },

  {
    label: '需求量',
    prop: 'yQty'
  },
  {
    label: '现用量',
    prop: 'xQty'
  },
  {
    label: '订购量/差异量',
    prop: 'cyQty'
  },
  {
    label: '备注信息',
    prop: 'remark'
  },
  {
    label: '订购单号',
    prop: 'reqNo'
  }
])
const cfmFlag = () => {
  const Unaudited = formList.value.find((item: any) => item.type === 'checkbox' && item.checkboxLabel === '正数')
  const Audited = formList.value.find((item: any) => item.type === 'checkbox' && item.checkboxLabel === '负数')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return 0
  } else if (Unaudited.checked) {
    return 1
  } else if (Audited.checked) {
    return 2
  } else {
    JMessage.warning('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return 0
  }
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>(`/mes/kf/ddMaterial/getMaterial?pageNum=${currentPage.value}&pageSize=${pageSize.value}`, {
    lotNo: formList.value.find((item: any) => item.selectP === '指令')?.selectValue,
    type: formList.value.find((item: any) => item.selectP === '分类')?.selectValue,
    mtlName: formList.value.find((item: any) => item.inputPlaceholder === '请输入材料名称')?.inputValue,
    mtlColor: formList.value.find((item: any) => item.inputPlaceholder === '请输入材料颜色')?.inputValue,
    typeNo: formList.value.find((item: any) => item.selectP === '材料分类')?.selectValue
      ? formList.value.find((item: any) => item.selectP === '材料分类').selectValue.split('  ')[1]
      : '',
    typeName: formList.value.find((item: any) => item.selectP === '材料分类')?.selectValue
      ? formList.value.find((item: any) => item.selectP === '材料分类').selectValue.split('  ')[0]
      : '',
    pluralFlag: cfmFlag(),
    purTypeFlag: 15,
    deptType: 2
  })
  isLoading.value = false
  tableData.value = tableDataList.rows.map((item: any) => {
    if (item.type === '1') item.type = '汇总'
    if (item.type === '2') item.type = '差异'
    // item.change = true
    // item.disableConfirm = true
    return item
  })
  total.value = tableDataList.total
  currentRow()
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0]) => {
  currentTableRow.value = row
}

// 选择通用资料
// 表二模块
const formList2 = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入物料编码',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料名称',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料颜色',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'button',
    checkboxLabel: '批处理'
  }
])
const selectTableList2 = ref([])
const selectList2 = (val: any) => {
  selectTableList2.value = val
}
const findClicked2 = async (content: string) => {
  if (content === '置空') {
    formList2.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '批处理') {
    // 批处理
    if (selectTableList2.value.length === 0) {
      JMessage.warning('请选择需要批处理的数据')
    } else {
      const res = await service.post<any, any>('/mes/kf/commonOrder/addBatchPcReqTemp', selectTableList2.value)
      if (res.code === 200) {
        JMessage.success('批处理成功')
        getTableList2()
        getTableList()
      } else {
        JMessage.error(res.msg)
      }
    }
  }
}
const tableData2 = ref([])
const isLoading2 = ref(true)
// 分页器
const currentPage2 = ref(1)
const pageSize2 = ref(40)
const total2 = ref(0)
const handleSizeChange2 = (val: number) => {
  pageSize2.value = val
  getTableList2()
}
const handleCurrentChange2 = (val: number) => {
  currentPage2.value = val
  getTableList2()
}
const tableHeader2 = ref([
  {
    label: '物料编码',
    prop: 'mtlNo',
    backgroundColor: true
  },
  {
    label: '颜色',
    prop: 'mtlColor'
  },
  {
    label: '材料名称',
    prop: 'mtlName'
  },
  {
    label: '规格',
    prop: 'mtlSpec'
  },
  {
    label: '单位',
    prop: 'mtlUnit'
  },
  {
    label: '库存量',
    prop: 'stkQty'
  },
  {
    label: '安全量',
    prop: 'safetyQty'
  }
])
const status2 = ref('')
const clickNumber2 = (val: any) => {
  status2.value = val
  getTableList2()
}
// 获取表数据
const getTableList2 = debounce(async () => {
  isLoading2.value = true
  let tableDataList = await service.post<any, any>(
    `/mes/kf/commonOrder/getCommonMaterial?pageNum=${currentPage2.value}&pageSize=${pageSize2.value}`,
    {
      mtlNo: formList2.value.find((item: any) => item.inputPlaceholder === '请输入物料编码')?.inputValue,
      mtlName: formList2.value.find((item: any) => item.inputPlaceholder === '请输入材料名称')?.inputValue,
      color: formList2.value.find((item: any) => item.inputPlaceholder === '请输入材料颜色')?.inputValue,
      publicFlag: 0
    }
  )
  isLoading2.value = false
  tableData2.value = tableDataList.rows.map((item: any) => {
    if (item.purFlag === 'Y') {
      item.backgroundColor = '#FE2416'
      item.change = null
    }

    return item
  })
  total2.value = tableDataList.total
  // currentRow2()
  // summaryData2.value[0].num = tableDataList.sum[0].orderCount
  // summaryData2.value[1].num = tableDataList.sum[0].surplusCount
}, 500)
onMounted(() => {
  // getTableList2()
})
watch(
  () =>
    formList2.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList2()
  }
)

// 所有订购单
const formList12 = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入订购单号',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入请购单号',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '厂商',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'date',
    dateLabel: '订购日期',
    dateValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入采购员',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入物料ID',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料名称',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料颜色',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'checkbox',
    checkboxLabel: '未下单',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '已下单',
    checked: true
  },
  {
    type: 'button',
    checkboxLabel: '置空'
  },
  {
    type: 'button',
    checkboxLabel: '查询'
  },
  {
    type: 'button',
    checkboxLabel: '导出当前行订购单'
  },
  {
    type: 'button',
    checkboxLabel: '返回'
  }
]) as any
const tableHeader12 = ref([
  {
    label: '订单类型',
    prop: 'purType',
    change: true
  },
  {
    label: '指令号',
    prop: 'orderId',
    disable: true
  },
  {
    label: '型体',
    prop: 'style',
    change: true
  },
  {
    label: '品牌',
    prop: 'brand',
    change: true
  },
  {
    label: '颜色',
    prop: 'color',
    change: true
  },
  {
    label: '材料颜色',
    prop: 'mtlColor',
    change: true
  },
  {
    label: '材料名称',
    prop: 'mtlName',
    change: true
  },
  {
    label: '规格',
    prop: 'mtlSpec',
    change: true
  },
  {
    label: '单位',
    prop: 'mtlUnit',
    change: true
  },
  {
    label: '订购单号',
    prop: 'purNo',
    change: true
  },
  {
    label: '订购日期',
    prop: 'purDate',
    change: true
  },
  {
    label: '订购数量',
    prop: 'purQty',
    change: true
  },
  {
    label: '厂商名称',
    prop: 'vendorName',
    change: true
  },
  {
    label: '需求交期',
    prop: 'jqDate'
  },
  {
    label: '责任人',
    prop: 'dutyUser',
    disable: true
  },
  {
    label: '责任原因',
    prop: 'dutyRek',
    disable: true
  },
  {
    label: '采购人',
    prop: 'createBy',
    disable: true
  },
  {
    label: '请购单号',
    prop: 'reqNo',
    disable: true
  },
  {
    label: '请购时间',
    prop: 'reqDate',
    disable: true
  },
  {
    label: '备注/订购备注',
    prop: 'remark',
    disable: true
  }
])
const tableData12 = ref([])
const selectTableList12 = ref([])
const selectList12 = (val: any) => {
  selectTableList12.value = val
}
const findClicked12 = async (content: string) => {
  if (content === '置空') {
    formList12.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
      item.checked = false
    })
  }
  if (content === '查询') {
    getTableList12()
  }
  if (content === '导出当前行订购单') {
    // 导出当前行订购单
    if (!currentTableRow12.value.purNo) {
      JMessage.error('当前行订购单号不可为空')
      return
    }
    // 导出当前行订购单
    const res = (await fileRequest.post(`/mes/kf/ddMaterial/downMtlPurSlipExcel`, {
      purNo: currentTableRow12.value.purNo,
      purTypeFlag: 15
    })) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`filename=`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
  if (content === '返回') {
    drawer2.value = false
  }
}
const currentTableRow12 = ref({}) as any
const currentRow12 = async (row: any = tableData12.value[0]) => {
  currentTableRow12.value = row
}
const isLoading12 = ref(true)
const total12 = ref(0)
const currentPage12 = ref(1)
const pageSize12 = ref(40)
const handleSizeChange12 = (val: number) => {
  pageSize12.value = val
  getTableList12()
}
const handleCurrentChange12 = (val: number) => {
  currentPage12.value = val
  getTableList12()
}
// 表格计算函数
const cfmFlag12 = () => {
  const Unaudited = formList12.value.find((item: any) => item.type === 'checkbox' && item.checkboxLabel === '未下单')
  const Audited = formList12.value.find((item: any) => item.type === 'checkbox' && item.checkboxLabel === '已下单')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return '0'
  } else if (Unaudited.checked) {
    return '1'
  } else if (Audited.checked) {
    return '2'
  } else {
    JMessage.warning('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return '0'
  }
}
const getTableList12 = debounce(async () => {
  isLoading12.value = true
  let tableDataList12 = await service.post<any, any>(
    `/mes/kf/ddMaterial/getPcPurDetail?pageNum=${currentPage12.value}&pageSize=${pageSize12.value}`,
    {
      lotNo: formList12.value.find((item: any) => item.inputPlaceholder === '请输入指令号')?.inputValue,
      style: formList12.value.find((item: any) => item.inputPlaceholder === '请输入型体')?.inputValue,
      purNo: formList12.value.find((item: any) => item.inputPlaceholder === '请输入订购单号')?.inputValue,
      reqNo: formList12.value.find((item: any) => item.inputPlaceholder === '请输入请购单号')?.inputValue,
      purType: formList12.value.find((item: any) => item.inputPlaceholder === '请输入订单类型')?.inputValue,
      vendorNo: formList12.value.find((item: any) => item.selectP === '厂商')?.selectValue.split(' ')[0],
      vendorName: formList12.value.find((item: any) => item.selectP === '厂商')?.selectValue.split(' ')[1],
      purDateStart: formList12.value.find((item: any) => item.dateLabel === '订购日期')?.dateValue[0],
      purDateEnd: formList12.value.find((item: any) => item.dateLabel === '订购日期')?.dateValue[1],
      mtlColor: formList12.value.find((item: any) => item.inputPlaceholder === '请输入材料颜色')?.inputValue,
      mtlName: formList12.value.find((item: any) => item.inputPlaceholder === '请输入材料名称')?.inputValue,
      purFlag: cfmFlag12(),
      userFlag: 2,
      purTypeFlag: 15
    }
  )
  isLoading12.value = false
  tableData12.value = tableDataList12.rows
  currentRow12()
})

const getSelectOptions = async () => {
  // 获取材料分类
  let mtlTypeList = await service.get<any, any>('/mes/api/commonQuery/selectTypeList')
  formList.value.find((item: any) => item.selectP === '材料分类')!.selectOptions = mtlTypeList.rows.map((item: any) => {
    return {
      optionKey: `${item.typeName}  ${item.typeNo}`,
      optionValue: `${item.typeName}  ${item.typeNo}`,
      optionLabel: `${item.typeName}  ${item.typeNo}`
    }
  })

  // 添加厂商
  let NewArray = []
  const result = await ManufacturerQuery()
  NewArray = result.rows.reduce((arr: any, item: any) => {
    if (item.vendorNo && item.vendorName) {
      // 只添加非空的 typeName 和 typeNo
      arr.push(item.vendorNo + '  ' + item.vendorName)
    }
    return arr
  }, [])

  formList12.value.find((item: any) => item.selectP === '厂商')!.selectOptions = NewArray.map((item: any) => {
    return {
      optionKey: item,
      optionValue: item,
      optionLabel: item
    }
  })
  // 添加指令
  let orderList = await service.post<any, any>('/mes/kf/ddMaterial/getOrder', {
    deptType: 2,
    purTypeFlag: 14
  })
  formList.value.find((item: any) => item.selectP === '指令')!.selectOptions = orderList.rows.map((item: any) => {
    return {
      optionKey: item,
      optionValue: item,
      optionLabel: item
    }
  })
}
onMounted(() => {
  getSelectOptions()
})
</script>
